package chapter03_binaryTree;


import com.sun.xml.internal.ws.api.config.management.Reconfigurable;

import java.sql.SQLOutput;
import java.util.LinkedList;
import java.util.Queue;

/**
 * 描述：
 *
 * @author hl
 * @date 2021/5/10 9:48
 */
public class SerialTree {

    public static void main(String[] args) {
        Node node = new Node(1);
        node.left = new Node(2);
        node.left.left = new Node(4);
        node.left.left.right = new Node(7);
        node.right = new Node(3);
        node.right.left = new Node(5);
        node.right.right = new Node(6);
        SerialTree serialTree = new SerialTree();
        String string = serialTree.serialTree(node);
        System.out.println(string);
        Node head = serialTree.reconTree(string);
        System.out.println(head);
    }

    public Node reconTree(String serialString){
        String[] split = serialString.split("!");
        Queue<String> queue = new LinkedList<>();
        for (int i = 0; i < split.length; i++) {
            queue.offer(split[i]);
        }
        return processRecon(split, queue);
    }

    private Node processRecon(String[] split, Queue<String> queue) {
        String value = queue.poll();
        if (value.equals("#")) {
            return null;
        }
        Node node = new Node(Integer.parseInt(value));
        node.left = processRecon(split, queue);
        node.right = processRecon(split, queue);
        return node;
    }
    public String serialTree(Node root){
        if (root == null) {
            return "#!";
        }
        String res  = root.val + "!";
        res += serialTree(root.left);
        res += serialTree(root.right);
        return res;
    }
}
